const firstStyle = document.querySelector('link[rel="stylesheet"]');
const dialogs = document.querySelectorAll('.mdl-dialog');
let isFileValid = false;
let upload = false;
if (dialogs.length > 0) {
	if (dialogs[0].showModal === undefined) {
		let s = firstStyle.cloneNode(true);
		s.href = 'https://cdn.bootcss.com/dialog-polyfill/0.4.6/dialog-polyfill.min.css';
		firstStyle.parentElement.insertBefore(s, firstStyle);
		let n = document.createElement('script');
		n.src = 'https://cdn.bootcss.com/dialog-polyfill/0.4.6/dialog-polyfill.min.js';
		n.onload = () => {
			dialogs.forEach(e => {
				dialogPolyfill.registerDialog(e);
			});
		};
		document.body.appendChild(n);
	}
	dialogs.forEach(e => {
		if (e.querySelector('.close')) {
			e.querySelector('.close').addEventListener('click', () => {
				e.close();
			});
		}
	});
}
//验证登录状态
const loginButton = document.getElementById('login-button');
ajax('/haslogin.do')
.then(r => JSON.parse(r))
.then(r => {
	if (r.success && r.data.haslogin) {
		//已经登录
		showMyPage();
	} else {
		loginButton.classList.remove('loading');
	}
});
loginButton.addEventListener('click', function() {
	if (this.classList.contains('loading')) {
		return;
	}
	const recaptchaEl = document.getElementById('g-recaptcha-response');
	if (recaptchaEl === null || recaptchaEl.value === "") {
		alert('请完成人机身份验证');
		return;
	}
	const uname = document.getElementById('username').value;
	const pwd = document.getElementById('password').value;
	ajax({
		"url": '/dologin.do',
		"type": "POST",
		"data": {
			"userid": uname,
			"userpass": pwd,
			"response": recaptchaEl.value
		}
	})
	.then(r => JSON.parse(r))
	.then(r => {
		if (r.success) {
			//登录成功
			showToast('登录成功');
			showMyPage();
		} else {
			showToast(r.message);
		}
	});
});
//显示个人页面
function showMyPage() {
	document.getElementById('login-page').style.display = 'none';
	document.getElementById('my-page').style.display = 'block';
	loadUploadType();
}
//上传类型加载
function loadUploadType() {
	ajax('/cansubmit.do')
	.then(r => JSON.parse(r))
	.then(r => {
		r.data.forEach(e => {
			let n = document.createElement('div');
			n.innerHTML = '<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="type-' + e.type + '"><input type="radio" id="type-' + e.type + '" class="mdl-radio__button" name="options" value="' + e.type + '"><span class="mdl-radio__label">' + e.name + '</span></label>';
			componentHandler.upgradeElement(n.querySelector('.mdl-radio'), 'MaterialRadio');
			document.getElementById('upload-type').appendChild(n);
		});
	});
}
//上传按钮点击
document.getElementById('file-button').addEventListener('click', () => {
	document.getElementById('file-input').click();
});
document.getElementById('file-input').addEventListener('change', function() {
	isFileValid = false;
	if (!this.files.length) {
		document.getElementById('file-name').innerText = '';
		return;
	}
	let file = this.files[0];
	checkFile(file)
	.then(() => {
		document.getElementById('file-name').innerText = file.name;
		isFileValid = true;
	})
	.catch((e) => {
		document.getElementById('file-name').innerHTML = '<font color="red">' + e + '</font>';
		showToast(e);
	});
});
//同组成员
document.getElementById('team-id').addEventListener('keyup', onTeamIdChange);
document.getElementById('team-id').addEventListener('paste', onTeamIdChange);
function onTeamIdChange() {
	if (this.value.includes('，')) {
		this.value = this.value.replace(/，/g, ',');
	}
	if (this.value.includes(',')) {
		let ids = this.value.split(',');
		this.value = ids[ids.length - 1];
		ids.splice(-1);
		ids.forEach(id => addTeamId(id));
	}
}
function addTeamId(id) {
	if (id === '') {
		return;
	}
	if (document.querySelectorAll('.team-list .mdl-chip').length >= 9) {
		showToast('同组成员最多10人');
		return;
	}
	if (id.length === 3) {
		id = '16180600' + id;
	}
	let e = document.createElement('span');
	e.setAttribute('data-id', id);
	e.className = 'mdl-chip mdl-chip--deletable';
	e.innerHTML = '<span class="mdl-chip__text">' + id + '</span><button type="button" class="mdl-chip__action"><i class="material-icons">cancel</i></button>';
	e.querySelector('.mdl-chip__action').addEventListener('click', function() {
		this.parentElement.remove();
	});
	document.querySelector('.team-list').appendChild(e);
}
function checkFile(file) {
	return new Promise((resolve, reject) => {
		if (file.size > 2 * 1024 * 1024) {
			reject('文件不能超过2MB');
			return;
		}
		const zip = new JSZip();
        JSZip.loadAsync(file)
        .then((zip) => {
			if (typeof(zip.files['index.html']) === 'undefined' && typeof(zip.files['index.htm']) === 'undefined') {
				reject('没有找到名为index.html或index.htm的首页文件，请检查');
				return;
			}
			let error = '';
            zip.forEach((relativePath, zipEntry) => {
				if (!/^([a-zA-Z0-9_\-\.\/\\]+)$/.test(relativePath)) {
					error = "文件“" + relativePath + "”名称不合法";
				}
            });
			if (error === "") {
				resolve();
			} else {
				reject(error);
			}
        }, function (e) {
            reject('文件读取失败，' + e.message);
        });
	});
}
//上传作品
document.getElementById('upload-button').addEventListener('click', () => {
	if(upload){
		showToast('请勿重复提交');
		return;
	}
	const type = document.querySelector('#upload-type input[type="radio"]:checked');
	if (type === null) {
		showToast('请选择类型');
		return;
	}
	const files = document.getElementById('file-input').files;
	if (!files.length) {
		showToast('请选择文件');
		return;
	}
	if (!isFileValid) {
		showToast('文件检查失败，请重新选择文件');
		return;
	}
	const team = document.querySelectorAll('.team-list .mdl-chip');
	if (team.length > 9) {
		showToast('同组成员最多10人');
		return;
	}
	upload=true;
	let teamId = [];
	team.forEach(e => {
		teamId.push(e.getAttribute('data-id'));
	});
	let data = new FormData();
	data.append('type', type.value);
	data.append('list', JSON.stringify(teamId));
	data.append('file', files[0]);
	ajax({
		"url": '/upload.do',
		"type": 'POST',
		"data": data
	})
	.then(r => JSON.parse(r))
	.then(r => {
		if (r.success) {
			//成功
			showToast('上传成功');
		} else {
			showToast(r.message);
			upload=false;
		}
	});
});
//修改密码
document.getElementById('change-password-button').addEventListener('click', function() {
	const old = document.getElementById('old-password').value;
	const new1 = document.getElementById('new-password').value;
	const new2 = document.getElementById('new-password2').value;
	if (new1 !== new2) {
		showToast('两次输入的密码不一致');
		return;
	}
	ajax('/changepassword.do?old=' + old + '&new=' + new1)
	.then(r => JSON.parse(r))
	.then(r => {
		if (r.success) {
			//成功
			showToast('修改成功');
		} else {
			showToast(r.message);
		}
	})
});